package com.kk.service.impl;

import com.kk.model.Menu;
import com.kk.model.Role;
import com.kk.model.RoleMenuRel;
import com.kk.model.User;
import com.kk.repository.MenuRepository;
import com.kk.repository.RoleMenuRelRepository;
import com.kk.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: kevin
 * @date: 2018-10-14 19:10
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private RoleMenuRelRepository roleMenuRelRepository;
    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<Menu> getMenuTreeByUser(User user) {
        Set<Role> roleSet = user.getRoles();
        if (roleSet == null || roleSet.size() == 0) {
            //TODO 全局异常处理
            return null;
        }
        //获取所有一级菜单
        Set<Menu> menuSet = new HashSet<>();
        for (Role role : roleSet) {
            List<RoleMenuRel> roleMenuRelSet = roleMenuRelRepository.findTopMenusByRoleId(role.getId());
            for (RoleMenuRel roleMenuRel : roleMenuRelSet) {
                menuSet.add(roleMenuRel.getMenu());
            }
        }
        List<Menu> menuList = new ArrayList<>();
        for (Menu menu : menuSet) {
            Set<Menu> menuChilds = menuRepository.findByParentId(menu.getId());
            menu.setChildren(menuChilds);
            menuList.add(menu);
        }
        return menuList;
    }
}
